<template>
    <div style="height: 100vh;">
        <!-- 导航栏 -->
        <van-nav-bar :title="isEditMode ? '修改食谱' : '发布食谱'" style="background-color: #FFD85F;" class="headera">
            <template #left>
                <van-icon name="arrow-left" size="18" @click="$router.back()" />
            </template>
        </van-nav-bar>

        <div style="background-color: #FFF7E1; min-height: 100vh; padding: 10px;">
            <!-- 表单 -->
            <van-form @submit="onSubmit" ref="form">
                <van-cell-group>

                    <!-- 图片上传 -->
                    <div class="field-card" style="text-align: center; margin-bottom: 20px;">
                        <van-uploader v-model="fileList" :max-count="1" :after-read="handleAfterRead"
                            :preview-image="true" :preview-full-image="true" accept="image/*" />
                    </div>

                    <!-- 食谱名称 -->
                    <div class="field-card">
                        <van-field v-model="form.recipe_name" label="食谱名称" placeholder="请输入食谱名称" required
                            :rules="[{ required: true, message: '食谱名称不能为空' }]" />
                    </div>

                    <!-- 食谱类别 -->
                    <div class="field-card">
                        <van-field readonly clickable name="picker" :value="form.category" label="选择食谱类别"
                            placeholder="点击选择食谱类别" @click="showPicker = true" />
                    </div>

                    <!-- 食谱描述 -->
                    <div class="field-card">
                        <van-field v-model="form.description" label="描述" type="textarea" placeholder="请输入描述" />
                    </div>

                    <!-- 制作步骤 -->
                    <div class="field-card">
                        <van-field v-model="form.instructions" label="步骤" type="textarea" placeholder="请输入制作步骤" />
                    </div>

                    <!-- 卡路里 -->
                    <div class="field-card">
                        <van-field v-model.number="form.calories" label="卡路里" type="number" placeholder="请输入卡路里含量" />
                    </div>

                    <!-- 蛋白质含量 -->
                    <div class="field-card">
                        <van-field v-model.number="form.protein" label="蛋白质含量" type="number" placeholder="请输入蛋白质含量" />
                    </div>

                    <!-- 脂肪含量 -->
                    <div class="field-card">
                        <van-field v-model.number="form.fat" label="脂肪含量" type="number" placeholder="请输入脂肪含量" />
                    </div>

                    <!-- 碳水化合物含量 -->
                    <div class="field-card">
                        <van-field v-model.number="form.carbohydrate" label="碳水化合物含量" type="number"
                            placeholder="请输入碳水化合物含量" />
                    </div>

                </van-cell-group>

                <!-- 发布按钮 -->
                <div style="padding: 16px;">
                    <van-button round type="primary" block @click="onSubmit">发布作品</van-button>
                </div>
            </van-form>

            <!-- 数据展示 -->
            <div v-if="submittedData" style="padding: 20px;">
                <h3>已提交的数据：</h3>
                <pre>{{ submittedData }}</pre>
            </div>

            <!-- 选择器弹窗 -->
            <van-popup v-model="showPicker" position="bottom">
                <van-picker show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
            </van-popup>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            id: null,
            originalL1CategoryId: null, // 存储原始的 pid
            form: {
                imageUrl: '', // 图片上传后的URL
                recipe_name: '',
                category: '',  // 食谱类别
                description: '',
                instructions: '',
                l1CategoryId: '', // 选中的类别 ID
                calories: null,
                protein: null,
                fat: null,
                carbohydrate: null,
                ingredientId: '',
            },
            submittedData: null,
            isSubmitting: false, // 防止重复提交
            value: '', // 用于绑定 picker 选择的值
            columns: [], // 初始为空，稍后填充食谱类别
            showPicker: false, // 控制 picker 弹窗显示
            fileList: [], // 存储上传的文件
            isEditMode: false, // 标记是否为编辑模式
        };
    },
    created() {
        this.id = this.$route.params.id || null;
        if (this.id) {
            this.isEditMode = true;
            this.loadRecipeData();
        }
    },
    mounted() {
        // 请求食谱类别接口，获取 ingredientsList
        this.fetchCategories();
    },
    methods: {
        // 请求食谱类别
        async fetchCategories() {
            try {
                const response = await axios.get('http://localhost:8081/wx/ingredients/index');
                if (response.data && response.data.errno === 0) {
                    this.columns = response.data.data.ingredientsList.map(item => ({
                        text: item.name, // van-picker 需要 `text` 作为显示值
                        id: item.id, // 存储 ID
                    }));
                } else {
                    console.error("接口返回错误:", response);
                    this.$toast.fail('获取食谱类别失败');
                }
            } catch (error) {
                console.error("请求食谱类别失败:", error);
                this.$toast.fail('请求失败，请稍后再试');
            }
        },

        // 修改映射
        async loadRecipeData() {
            try {
                const response = await axios.get(`http://localhost:8081/wx/recipes/selectupdate?id=${this.id}`, {
                    headers: {
                        token: localStorage.getItem('token'), // 添加 Bearer Token 认证
                        'Content-Type': 'application/json' // 确保 Content-Type 正确
                    }
                });
                if (response.data.data) {
                    const dish = response.data.data;
                    this.form = {
                        imageUrl: dish.imageUrl,
                        recipe_name: dish.recipeName,
                        category: dish.category,
                        description: dish.description,
                        instructions: dish.instructions,
                        calories: dish.calories,
                        protein: dish.protein,
                        fat: dish.fat,
                        ingredientId: dish.ingredientId,
                        carbohydrate: dish.carbohydrate,
                    };
                    this.originalL1CategoryId = dish.ingredientId; // 存储原始类别 ID
                    this.fileList = dish.imageUrl ? [{ url: dish.imageUrl }] : [];
                }
            } catch (error) {
                console.error("加载食谱数据失败:", error);
                this.$toast.fail("加载数据失败");
            }
        },

        // 处理图片上传
        async handleAfterRead(file) {
            const formData = new FormData();
            formData.append('file', file.file);

            try {
                const response = await axios.post('http://localhost:8081/wx/storage/create', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });

                if (response.data.errno === 0) {
                    this.form.imageUrl = response.data.data.url;
                } else {
                    this.$toast.fail('图片上传失败');
                }
            } catch (error) {
                this.$toast.fail('图片上传失败');
            }
        },

        // 提交表单
        async onSubmit() {
            if (this.isSubmitting) return; // 防止重复提交
            this.isSubmitting = true;

            // 手动验证表单
            if (!this.form.recipe_name || !this.form.category || !this.form.description || !this.form.instructions) {
                this.$toast.fail("请填写完整信息");
                this.isSubmitting = false;
                return;
            }

            // 如果用户未选择新的食谱类别，则使用原始类别 ID
            if (!this.form.l1CategoryId) {
                this.form.l1CategoryId = this.originalL1CategoryId;
            }

            // 如果是修改
            if (this.id) {
                if (this.fileList.length === 0 && !this.form.imageUrl) {
                    this.$toast.fail('图片上传失败');
                    this.isSubmitting = false;
                    return;
                }

                const responses = await axios.post("http://localhost:8081/wx/recipes/update?pid=" + this.form.l1CategoryId, {
                    id: this.id,
                    recipeName: this.form.recipe_name,
                    description: this.form.description,
                    instructions: this.form.instructions,
                    calories: this.form.calories,
                    protein: this.form.protein,
                    fat: this.form.fat,
                    carbohydrate: this.form.carbohydrate,
                    imageUrl: this.form.imageUrl,
                    category: this.form.category,
                    ingredientId: this.form.ingredientId,
                    userId: localStorage.getItem("userId"),
                });

                if (responses.status === 200) {
                    this.$toast.success("修改成功");
                    this.$router.back();
                    this.isSubmitting = false; // 释放提交锁
                } else {
                    this.$toast.fail(response.data.message || "修改失败");
                    this.isSubmitting = false;
                }
            } else {
                // 如果用户没有上传新图片，保持原来的图片
                if (this.fileList.length === 0 && !this.form.imageUrl) {
                    this.$toast.fail('图片上传失败');
                    this.isSubmitting = false;
                    return;
                }

                const responses = await axios.post("http://localhost:8081/wx/recipes/add", {
                    recipeName: this.form.recipe_name,
                    ingredientName: this.form.category,
                    description: this.form.description,
                    instructions: this.form.instructions,
                    ingredientDesc: this.form.recipe_name,
                    picUrl: this.form.imageUrl,
                    calories: this.form.calories,
                    protein: this.form.protein,
                    fat: this.form.fat,
                    carbohydrate: this.form.carbohydrate,
                    imageUrl: this.form.imageUrl,
                    userId: localStorage.getItem("userId"),
                    l1CategoryId: this.form.l1CategoryId
                });

                if (responses.status === 200) {
                    this.$toast.success("发布成功");
                    this.$router.back();
                } else {
                    this.$toast.fail(responses.data.message || "发布失败");
                }
            }
        },

        onConfirm(value) {
            console.log(value.text)
            this.form.category = value.text;
            this.form.l1CategoryId = value.id;  // 保存选择的类别 ID
            this.showPicker = false;
        }
    },
};
</script>

<style scoped>
.field-card {
    background-color: #ffffff;
    border-radius: 12px;
    padding: 14px 16px;
    margin: 12px 16px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
    transition: box-shadow 0.3s ease;
}

.field-card:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}
</style>
